package com.gams.springboot.config;

import com.gams.springboot.pojo.Menu;
import com.gams.springboot.pojo.Role;
import com.gams.springboot.pojo.User;
import com.gams.springboot.services.MenuService;
import com.gams.springboot.services.RoleService;
import com.gams.springboot.services.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.ModelAndView;

import java.util.List;

/**
 * @author tql
 * @current springboot
 * @create 2021-09-19-17:00
 */
public class UserRealm extends AuthorizingRealm {
    @Autowired
    private UserService userService;

    @Autowired
    private RoleService roleService;

    @Autowired
    private MenuService menuService;
    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("授权");
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        Subject subject = SecurityUtils.getSubject();
        User currentUser = (User)subject.getPrincipal();//取到的值是user（当前登录用户的信息）
        List<Role> roleList = roleService.selectAllRoleByUserId(currentUser.getId());
        List<Menu> menuList = null;
        if(roleList.size()>0){
            for(Role role : roleList){
                info.addRole(role.getName());
                menuList = menuService.selectAllMenuByRoleId(role.getId());
                for(Menu menu : menuList){
                    info.addStringPermission(menu.getAuthority());
                }
            }
        }
//        info.addStringPermission("user:add");
        return info;
    }

    //认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        System.out.println("认证");
        UsernamePasswordToken userToken = (UsernamePasswordToken) token;
        User user = userService.selectUserByName(userToken.getUsername());
        if(user==null){
            return null;
        }
        Subject currentSubject = SecurityUtils.getSubject();
        Session session = currentSubject.getSession();
        session.setAttribute("loginUser",user);
        session.setAttribute("menuList",menuService.selectAllMenuByUserId(user.getId()));
        if(user.getStatus()==1){
            throw new AuthenticationException();
        }
        return new SimpleAuthenticationInfo(user,user.getPassword(),"");
    }
}
